#!/bin/bash

# 检测系统类型
if [ -f /etc/os-release ]; then
    . /etc/os-release
    OS=$NAME
    VERSION=$VERSION_ID
else
    echo "Cannot detect OS version"
    exit 1
fi

echo "Detected OS: $OS"

# 根据不同的发行版安装软件
if [[ "$OS" == *"Ubuntu"* ]] || [[ "$OS" == *"Debian"* ]]; then
    # Ubuntu/Debian 系统
    sudo apt-get update
    sudo apt-get install -y \
        apt-transport-https \
        ca-certificates \
        curl \
        gnupg \
        lsb-release \
        git

    # 添加 Docker 的官方 GPG 密钥
    curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /usr/share/keyrings/docker-archive-keyring.gpg

    # 设置 Docker 的稳定版仓库
    echo \
    "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/docker-archive-keyring.gpg] https://download.docker.com/linux/ubuntu \
    $(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null

    sudo apt-get update
    sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

elif [[ "$OS" == *"CentOS"* ]] || [[ "$OS" == *"Red Hat"* ]] || [[ "$OS" == *"Fedora"* ]] || [[ "$OS" == *"Alibaba Cloud Linux"* ]]; then
    # CentOS/RHEL/Fedora/Alibaba Cloud Linux 系统
    sudo yum install -y yum-utils git

    # 配置阿里云镜像源（如果是阿里云 Linux）
    if [[ "$OS" == *"Alibaba Cloud Linux"* ]]; then
        sudo yum-config-manager --add-repo http://mirrors.aliyun.com/docker-ce/linux/centos/docker-ce.repo
        sudo sed -i 's+download.docker.com+mirrors.aliyun.com/docker-ce+' /etc/yum.repos.d/docker-ce.repo
    else
        sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
    fi
    
    # 安装 Docker
    sudo yum install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

elif [[ "$OS" == *"SUSE"* ]]; then
    # OpenSUSE 系统
    sudo zypper install -y git
    
    # 添加 Docker 仓库
    sudo zypper addrepo https://download.docker.com/linux/sles/docker-ce.repo
    
    # 安装 Docker
    sudo zypper install -y docker-ce docker-ce-cli containerd.io docker-compose-plugin

else
    echo "Unsupported operating system"
    exit 1
fi

# 启动 Docker 服务
sudo systemctl start docker
sudo systemctl enable docker

# 将当前用户添加到 docker 组
sudo usermod -aG docker $USER

# 配置 Docker 镜像加速（使用阿里云镜像加速）
sudo mkdir -p /etc/docker
sudo tee /etc/docker/daemon.json <<-'EOF'
{
  "registry-mirrors": ["http://hub-mirror.c.163.com",
"https://mirrors.tuna.tsinghua.edu.cn",
"http://mirrors.sohu.com",
"https://ustc-edu-cn.mirror.aliyuncs.com",
"https://ccr.ccs.tencentyun.com",
"https://docker.m.daocloud.io",
"https://docker.awsl9527.cn"]
}
EOF
sudo systemctl daemon-reload
sudo systemctl restart docker

# 验证安装
echo "Verifying installations..."
docker --version
git --version

echo "Installation completed! Please log out and log back in for docker group changes to take effect."
echo "You can then run 'docker ps' to verify that you can run docker commands without sudo."
